package com.jevons.geo_edit.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.jevons.geo_edit.R;
import com.jevons.geo_edit.constant.GisGeometryType;
import com.jevons.geo_edit.model.GisLayer;
import com.jevons.geo_edit.model.GisLayerStyle;
import com.jevons.geo_edit.widget.GeometryTypeView;
import com.jevons.muffin.utilcode.ImageUtils;
import com.jevons.muffin.utilcode.LogUtils;
import com.jevons.muffin.utilcode.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * Copyright 2020 JxGIS
 *
 * @file LayerManagerAdapter
 * @auth linaisheng
 * Created on 2023/6/9.
 * Description：
 */
public class LayerManagerAdapter extends BaseQuickAdapter<GisLayer, BaseViewHolder> {

    private Context mContext;
    private String selectedLayerId;

    private OnItemOpListener opListener;

    private boolean onDragging = false;
    //记录移动的坐标
    private List<Integer[]> dragMovePosition = new ArrayList<>();

    public LayerManagerAdapter(Context context, OnItemOpListener listener) {
        super(R.layout.item_gis_map_layer_manager, new ArrayList<>());
        this.mContext = context;
        this.opListener = listener;
    }

    @Override
    protected void convert(@NonNull BaseViewHolder helper, GisLayer layer) {
        LinearLayout itemRoot = (LinearLayout) helper.getView(R.id.ll_item_root);
        if (StringUtils.isNotEmpty(selectedLayerId) && selectedLayerId.equals(layer.getId())) {
            itemRoot.setBackgroundColor(Color.parseColor("#C2C2C2"));
        } else {
            itemRoot.setBackgroundColor(Color.parseColor("#FFFFFF"));
        }
        itemRoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (opListener != null) {
                    opListener.onClickItem(helper.getAdapterPosition());
                }
            }
        });

        GisLayerStyle layerStyle = layer.getMyLayerStyle();
        GeometryTypeView gemType = (GeometryTypeView) helper.getView(R.id.iv_layer_type);
        if (layer.getGeometryType() == GisGeometryType.Point) {
            Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(),
                    GisLayer.getPointStyleRes(layerStyle.getPointType(), layerStyle.getPointStyle()));
            gemType.changePointType(ImageUtils.makeTintBitmap(bitmap, Color.parseColor(layerStyle.getFillColor())));
        } else if (layer.getGeometryType() == GisGeometryType.Line) {
            gemType.changeLineType(layerStyle.getFillColor());
        } else {
            gemType.changePolygonType(layerStyle.getFillColor(), layerStyle.getLineColor());
        }


        TextView tvLayerName = (TextView) helper.getView(R.id.tv_layer_name);
        tvLayerName.setText(layer.getLayerName());

        ImageView ivVisible = (ImageView) helper.getView(R.id.iv_visible);
        ivVisible.setImageResource(layer.isLayerVisible() ? R.drawable.icon_state_visible
                : R.drawable.icon_state_invisible);
        ivVisible.setOnClickListener(view -> {
            if (opListener != null) {
                opListener.onClickItemVisible(helper.getAdapterPosition());
            }
        });

        ImageView ivGeometry = helper.getView(R.id.iv_geometry);
        ivGeometry.setOnClickListener(view -> {
            if (opListener != null) {
                opListener.onClickItemGeometry(helper.getAdapterPosition());
            }
        });


        ImageView ivDelete = helper.getView(R.id.iv_delete);
        ivDelete.setOnClickListener(view -> {
            if (opListener != null) {
                opListener.onClickItemDelete(helper.getAdapterPosition());
            }
        });
    }


    @Override
    public void bindToRecyclerView(RecyclerView recyclerView) {
        super.bindToRecyclerView(recyclerView);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelperCallBack());
        itemTouchHelper.attachToRecyclerView(recyclerView);
    }

    public String getSelectedLayerId() {
        return selectedLayerId;
    }

    public void setSelectedLayerId(String layerId) {
        this.selectedLayerId = layerId;
        notifyDataSetChanged();
    }



    public class ItemTouchHelperCallBack extends ItemTouchHelper.Callback {

        @Override
        public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
            // 长按拖动，不可删除,可换位使用
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            return makeMovementFlags(dragFlags, 0);
        }

        // 拖拽 排序item时调用
        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
            int form = viewHolder.getAdapterPosition();
            int to = target.getAdapterPosition();
            LogUtils.printError("onMove");
            dragMovePosition.add(new Integer[]{ form, to });

            boolean isMove = false;
            try {
                if (getData().size() > 0) {
                    if (form < to) {
                        //从上往下拖动，每滑动一个item，都将list中的item向下交换，向上滑同理。
                        for (int i = form; i < to; i++) {
                            Collections.swap(getData(), i, i + 1);//交换数据源两个数据的位置
                        }
                    } else {
                        for (int i = form; i > to; i--) {
                            Collections.swap(getData(), i, i - 1);//交换数据源两个数据的位置
                        }
                    }

                    // adapter.notifyDataSetChanged();//这个方法也可解决拖动后item边距错位问题，但是会丢失拖动动画效果
                    notifyItemMoved(form, to);
                    isMove = true;
                }
            } catch (Exception e) {
            }
            return isMove;
        }


        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            // null
        }

        @Override
        public void onSelectedChanged(@Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
            super.onSelectedChanged(viewHolder, actionState);
            if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
                //开始拖动
                dragMovePosition.clear();
                onDragging = true;
            }  else if (actionState == ItemTouchHelper.ACTION_STATE_IDLE) {
                if (onDragging && dragMovePosition.size() > 0) {
                    Integer[] firstMoveArray = dragMovePosition.get(0);
                    Integer[] lastMoveArray = dragMovePosition.get(dragMovePosition.size() - 1);
                    int fromPosition = firstMoveArray[0];
                    int toPosition = lastMoveArray[1];

                    if (fromPosition != toPosition && opListener != null) {
                        opListener.onItemMove(fromPosition, toPosition);
                    }
                }
                onDragging = false;
            }

        }
    }

    public interface OnItemOpListener {

        void onClickItem(int position);

        void onClickItemVisible(int position);

        void onClickItemGeometry(int position);

        void onClickItemEdit(int position);

        void onClickItemEditField(int position);

        void onClickItemDelete(int position);

        void onItemMove(int fromPosition, int toPosition);
    }

}